package org.lhh.server.service.impl;

import com.mxgraph.util.mxXmlUtils;
import org.apache.commons.lang3.StringUtils;
import org.lhh.server.common.api.JSONResult;
import org.lhh.server.common.utils.*;
import org.lhh.server.core.codec.steps.StepEncoder;
import org.lhh.server.core.codec.trans.TransMetaCodec;
import org.lhh.server.core.executor.TransExecutor;
import org.lhh.server.core.repository.EtlRepository;
import org.lhh.server.service.ITransService;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.StepPluginType;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.repository.LongObjectId;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.w3c.dom.Element;

import java.util.List;

/**
 * @author 辉仔
 * @since 2019-06-16
 */
@Service
public class TransServiceImpl  implements ITransService {

    private static final Logger logger = LoggerFactory.getLogger(TransServiceImpl.class);

    @Override
    public JSONResult rename(String id, String categoryId, String name) {
//        if (exist(name, categoryId, id)) {
//            return JSONResult.errorMsg("转换名称已存在");
//        }
//        Trans trans = this.selectById(id);
//        if (trans == null)
//            return JSONResult.errorMsg("转换不存在了");
//        trans.setName(name);
//        trans.setUpdateBy(SessionUtils.getUsername());
//        trans.setUpdateTime(new Date());
//        this.updateById(trans);
//        return JSONResult.ok(trans);
        return null;
    }



    @Override
    public boolean getTransformationStatus(String transName) {
        TransExecutor transExecutor = TransExecutor.getTranExecutor(transName);
        if (transExecutor != null) {
            return transExecutor.isFinished();
        }
        return true;
    }

    @Override
    public String addStep(String graphXml, String pluginId, String name) {
        TransMeta transMeta = (TransMeta) TransMetaCodec.decode(graphXml);
        if (StringUtils.isEmpty(pluginId)) {
            StepMeta step = transMeta.findStep(name);
            pluginId = step.getStepID();
        }
        if (transMeta.findStep(name) != null) {
            int i = 2;
            String newName = name + i;
            while (transMeta.findStep(newName) != null) {
                i++;
                newName = name + i;
            }
            name = newName;
        }
        PluginRegistry registry = PluginRegistry.getInstance();
        PluginInterface stepPlugin = registry.findPluginWithId(StepPluginType.class, pluginId);
        StepMetaInterface info = null;
        try {
            info = (StepMetaInterface) registry.loadClass(stepPlugin);
            info.setDefault();
        } catch (Exception e) {
            //ignored
        }
        StepMeta stepMeta = new StepMeta(stepPlugin.getIds()[0], name, info);
        StepEncoder stepEncoder = (StepEncoder) SpringBeanUtil.getBean(stepMeta.getStepID());
        Element e = stepEncoder.encodeStep(stepMeta);
        return XMLHandler.getXMLHeader() + mxXmlUtils.getXml(e);
    }

    @Override
    public JSONResult getTransformation(String transName,Long directoryId) {
        TransMeta transMeta = EtlRepository.getTransMeta(transName,new LongObjectId(directoryId));
        return JSONResult.ok(TransMetaCodec.encode(transMeta));
    }

    @Override
    public JSONArray steps() {
        PluginRegistry registry = PluginRegistry.getInstance();
        List<PluginInterface> steps = registry.getPlugins(StepPluginType.class);
        List<String> categories = registry.getCategories(StepPluginType.class);
        JSONArray menus = new JSONArray();
        if (!CollectionUtils.isEmpty(categories)) {
            for (int i = 0; i < categories.size(); i++) {
                JSONObject category = new JSONObject();
                category.put("index", i);
                category.put("title", categories.get(i));
                JSONArray children = new JSONArray();
                for (PluginInterface pluginInterface : steps) {
                    if (pluginInterface.getCategory().equals(categories.get(i))) {
                        if (SpringBeanUtil.containBean(pluginInterface.getIds()[0])) {
                            final JSONObject child = new JSONObject();
                            child.put("name", pluginInterface.getName());
                            child.put("pluginId", pluginInterface.getIds()[0]);
                            child.put("icon", ImageUtil.getURl(pluginInterface.getImageFile()));
                            child.put("description", pluginInterface.getDescription());
                            children.add(child);
                        }
                    }
                }
                if (CollectionUtils.isEmpty(children))
                    continue;
                category.put("children", children);
                menus.add(category);
            }
        }
        return menus;
    }
}
